//
//  DiscoverExploreDetialViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/18.
//

#import "DiscoverExploreDetialViewController.h"
#import <WebKit/WebKit.h>
#import "DiscoverEexploreDetialListCell.h"
#import "DiscoverExploreRecommendManager.h"
#import <WXApi.h>
#import "ShareView.h"
#import <PDFKit/PDFKit.h>


@interface DiscoverExploreDetialViewController ()<WKUIDelegate,WKNavigationDelegate,UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)DiscoverExploreRecommendManager *recommendManager;
@property(nonatomic,strong)ShareView *shareView;
@property(nonatomic,strong)PDFView *pdfView;
@property(nonatomic,strong)JPProgressHUD *hub;
@property(nonatomic,strong)UIView *lineView;//遮挡pdfView底部黑线
@property(nonatomic,assign)CGFloat t_h;

@end

@implementation DiscoverExploreDetialViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(DiscoverExploreRecommendManager *)recommendManager{
    if(!_recommendManager){
        _recommendManager = [[DiscoverExploreRecommendManager alloc]init];
        _recommendManager.delegate = self;
    }
    return _recommendManager;
}


-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    [self loadListData];
}

#pragma mark - 获取列表数据
-(void)loadListData{
    [self.recommendManager loadData];
}

- (void)createUI {
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:@"探索详情"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth, self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 76)];
    self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth, 1);
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    CGFloat t_h = [self getStringHeightWithText:self.exploreListModel.name font:JPUIFontPingFangSCMedium(16) viewWidth:self.currentAvailableWidth-32];
    if(t_h < 22){
        t_h = 22;
    }
    self.t_h = t_h;
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(16,16,self.currentAvailableWidth-32,t_h)];
    self.titleLabel.font = JPUIFontPingFangSCMedium(16);
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.text = self.exploreListModel.name;
    self.titleLabel.numberOfLines = 0;
    [self.scrollView addSubview:self.titleLabel];

    [self createWebView];
    
    self.pdfView = [[PDFView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.webView.frame), self.currentAvailableWidth,0)];
    self.pdfView.backgroundColor = [UIColor whiteColor];
    self.pdfView.pageShadowsEnabled = NO;
    self.pdfView.userInteractionEnabled = NO;
    [self.scrollView addSubview:self.pdfView];
    self.pdfView.hidden = YES;
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.pdfView.frame)-6,self.currentAvailableWidth,6)];
    self.lineView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.lineView];
    self.lineView.hidden = YES;
    
   
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(self.pdfView.frame),self.currentAvailableWidth,44) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"DiscoverEexploreDetialListCell") forCellReuseIdentifier:@"DiscoverEexploreDetialListCell"];
    self.tableView.bounces = NO;
    [self.scrollView addSubview:self.tableView];
    [self createTableHeaderView];
    

    UIButton *shareBtn = [[UIButton alloc]init];
    [shareBtn setImage:[UIImage imageNamed:@"discover_explore_share"] forState:UIControlStateNormal];
    [shareBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [shareBtn setTitle:@" 分享文章" forState:UIControlStateNormal];
    shareBtn.titleLabel.font = JPUIFontPingFangSCRegular(15);
    [shareBtn addTarget:self action:@selector(shareBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareBtn];
    [shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(@-34);
        make.height.mas_equalTo(@42);
    }];
    
    UIView *bline = [[UIView alloc]init];
    bline.backgroundColor = KLineColor;
    [self.view addSubview:bline];
    [bline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(@0);
        make.height.mas_equalTo(@1);
        make.bottom.mas_equalTo(@-75);
    }];
    
    [self loadHtml];

    if(self.exploreListModel.filePath&&![self.exploreListModel.filePath isEqualToString:@""]){
        self.tableView.hidden = YES;
        self.hub = [JPProgressHUD showLoadingInView:self.view];
        [self loadPDF];
    }else{
        self.tableView.hidden = NO;
    }
    
    
}

#pragma mark - 创建喜欢的人
-(void)createTableHeaderView{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,44)];
    headView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headView;
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,6)];
    line.backgroundColor = KLineColor;
    [headView addSubview:line];
    UILabel *tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(16,22,self.currentAvailableWidth-32,20)];
    tipLabel.font = JPUIFontPingFangSCRegular(14);
    tipLabel.textColor = KFontGrayColor;
    tipLabel.text = @"喜此内容的人还喜欢";
    [headView addSubview:tipLabel];
}

#pragma mark - 创建webview
-(void)createWebView{
    NSString *jScript0 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript0 = [[WKUserScript alloc] initWithSource:jScript0 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController0 = [[WKUserContentController alloc] init];
    [wkUController0 addUserScript:wkUScript0];
    WKWebViewConfiguration *wkWebConfig0 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig0.userContentController = wkUController0;
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(0,26+self.t_h,self.currentAvailableWidth,1) configuration:wkWebConfig0];
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    self.webView.scrollView.bounces = NO;
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.scrollEnabled = NO;
    self.webView.opaque = NO;
    [self.scrollView addSubview:self.webView];
    
    [self.webView addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"JPWebKitContext"];
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0,0,self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.scrollView.frame = CGRectMake(0, kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth, self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 76);
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth, 1);
            CGFloat t_h = [self getStringHeightWithText:self.exploreListModel.name font:JPUIFontPingFangSCMedium(16) viewWidth:self.currentAvailableWidth-32];
            if(t_h < 22){
                t_h = 22;
            }
            self.t_h = t_h;
            self.titleLabel.frame = CGRectMake(16,16,self.currentAvailableWidth-32,t_h);
            self.webView.frame = CGRectMake(0,26+self.t_h,self.currentAvailableWidth,1);
            self.pdfView.frame = CGRectMake(0,CGRectGetMaxY(self.webView.frame), self.currentAvailableWidth,0);
            self.lineView.frame = CGRectMake(0,CGRectGetMaxY(self.pdfView.frame)-6,self.currentAvailableWidth,6);
            self.tableView.frame = CGRectMake(0,CGRectGetMaxY(self.pdfView.frame),self.currentAvailableWidth,self.tableView.height);
            [self.tableView reloadData];
            [self createTableHeaderView];
            [self.webView removeFromSuperview];
            self.webView = nil;
            [self createWebView];
            [self loadHtml];
            if(self.exploreListModel.filePath&&![self.exploreListModel.filePath isEqualToString:@""]){
                [self adjustPDFViewHeight];
            }
            if(self.shareView&&self.shareView.isShow == YES){
                self.shareView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
                self.shareView.currentAvailableWidth = self.currentAvailableWidth;
                self.shareView.currentAvailableHeight = self.currentAvailableHeight;
                [self.shareView refreshWidth];
            }else{
                if(self.shareView){
                    self.shareView = nil;
                }
            }
        });
    }
}

#pragma mark - 分享
-(void)shareBtnClick{
    [self showShareView];
}

-(void)showShareView{
    
    if(!self.shareView){
        self.shareView = [[ShareView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight)];
    }
    self.shareView.currentAvailableWidth = self.currentAvailableWidth;
    self.shareView.currentAvailableHeight = self.currentAvailableHeight;
    UIWindow *keyWindow = KEY_WINDOW;
    if(keyWindow){
        [keyWindow addSubview:self.shareView];
    }
    [self.shareView show];
    __weak typeof(self)self_weak_ = self;
    [self.shareView setShareBlock:^(NSInteger index) {
        [self_weak_.shareView hidden];
        [self_weak_ shareToWeChatAndIndex:index];
    }];
    
}

#pragma mark - 微信 微信朋友圈分享
- (void)shareToWeChatAndIndex:(NSInteger)index{
    // 创建微信消息对象
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = self.exploreListModel.name?self.exploreListModel.name:@"日语岛";
    message.description = self.exploreListModel.content?self.exploreListModel.content:@"一起来背单词吧！";
    // 设置缩略图
    if(self.shareImage){
        [message setThumbImage:self.shareImage];
    }
    // 创建网页对象
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = SHARELINK;
    message.mediaObject = webpageObject;
    // 创建发送请求对象
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if(index == 1){
        //朋友圈
        req.scene = WXSceneTimeline;
    }else{
        //会话
        req.scene = WXSceneSession;
    }
    // 发送请求
    [WXApi sendReq:req completion:^(BOOL success) {
        if(success == NO){
            dispatch_async(dispatch_get_main_queue(), ^{
                [JPProgressHUD showMsg:@"分享失败"];
            });
        }
    }];
}


#pragma mark - 加载网页
- (void)loadHtml{
    if(self.exploreListModel.editContent&&![self.exploreListModel.editContent isEqualToString:@""]){
        NSString *htmlContent = self.exploreListModel.editContent;
        htmlContent = [htmlContent stringByReplacingOccurrencesOfString:@"<img " withString:@"<img style=\"max-width: 100%;\" "];
        // 添加包含左右 padding 样式的 div
        NSString *paddingStyle = @"<style>body{padding-left: 9px; padding-right: 9px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        htmlContent = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle, htmlContent];
        [self.webView loadHTMLString:htmlContent baseURL:nil];
    }
}



#pragma mark - webview delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // 当网页加载完成时，调整 webView 的 frame
    [webView evaluateJavaScript:@"document.documentElement.scrollHeight" completionHandler:^(id result, NSError *error) {
        CGFloat height = [result doubleValue];
        webView.frame = CGRectMake(0,26+self.titleLabel.height,self.currentAvailableWidth,height);
        if(self.exploreListModel.filePath && ![self.exploreListModel.filePath isEqualToString:@""]) {
            self.pdfView.top = CGRectGetMaxY(self.webView.frame);
            self.pdfView.hidden = NO;
            self.lineView.hidden = NO;
            self.lineView.top = CGRectGetMaxY(self.pdfView.frame)-6;
            self.tableView.top = CGRectGetMaxY(self.pdfView.frame);
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ webView.height+self.tableView.height+self.pdfView.height);
        }else{
            self.pdfView.hidden = YES;
            self.lineView.hidden = YES;
            self.tableView.top = CGRectGetMaxY(webView.frame);
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ webView.height+self.tableView.height);
        }
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"scrollView.contentSize"]) {
        CGFloat height = self.webView.scrollView.contentSize.height;
        self.webView.frame = CGRectMake(0,26+self.titleLabel.height,self.currentAvailableWidth,height);
        if(self.exploreListModel.filePath && ![self.exploreListModel.filePath isEqualToString:@""]) {
            self.pdfView.top = CGRectGetMaxY(self.webView.frame);
            self.pdfView.hidden = NO;
            self.lineView.hidden = NO;
            self.lineView.top = CGRectGetMaxY(self.pdfView.frame)-6;
            self.tableView.top = CGRectGetMaxY(self.pdfView.frame);
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ self.webView.height+self.tableView.height+self.pdfView.height);
        }else{
            self.pdfView.hidden = YES;
            self.lineView.hidden = YES;
            self.tableView.top = CGRectGetMaxY(self.webView.frame);
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ self.webView.height+self.tableView.height);
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}



#pragma mark - 加载pdf文件
-(void)loadPDF {
    if(self.exploreListModel.filePath && ![self.exploreListModel.filePath isEqualToString:@""]) {
        // 异步加载 PDF 文件
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURL *pdfURL = [NSURL URLWithString:self.exploreListModel.filePath];
            PDFDocument *pdfDocument = [[PDFDocument alloc] initWithURL:pdfURL];
            dispatch_async(dispatch_get_main_queue(), ^{
                // 加载完成后在主线程更新 UI
                if (pdfDocument) {
                    self.pdfView.document = pdfDocument;
                    self.pdfView.autoScales = YES;
                    self.pdfView.minScaleFactor = self.pdfView.scaleFactor;
                    self.pdfView.maxScaleFactor = self.pdfView.scaleFactor;
                    // 调整 PDFView 的高度
                    [self adjustPDFViewHeight];
                    
                } else {
                    self.tableView.hidden = NO;
                    // 如果加载失败，也隐藏 loading 指示器
                    if(self.hub){
                        [self.hub removeFromSuperview];
                    }
                }
            });
        });
    } else {
        self.tableView.top = CGRectGetMaxY(self.webView.frame);
        self.tableView.hidden = NO;
        self.pdfView.height = 0;
        self.pdfView.hidden = YES;
        self.lineView.hidden = YES;
        if(self.hub){
            [self.hub removeFromSuperview];
        }
    }
}


#pragma mark - 调整 PDFView 的高度
- (void)adjustPDFViewHeight{
    if (self.pdfView.document){
        // 获取PDF文档的页数
        NSUInteger pageCount = self.pdfView.document.pageCount;
        CGFloat totalHeight = 0.0;
        // 遍历每一页，计算总高度
        for (NSUInteger i = 0; i < pageCount; i++) {
            PDFPage *page = [self.pdfView.document pageAtIndex:i];
            CGRect pageRect = [page boundsForBox:kPDFDisplayBoxMediaBox];
            // 计算当前页的缩放比例和高度
            CGFloat scale = self.pdfView.bounds.size.width / pageRect.size.width;
            CGFloat pageHeight = pageRect.size.height * scale;

            // 累加所有页面的高度
            totalHeight += pageHeight;
        }

        // 设置PDFView的高度
        if(pageCount == 1&&self.pdfView.documentView.height<totalHeight){
            self.pdfView.height = self.pdfView.documentView.height;
        }else{
            self.pdfView.height = totalHeight;
        }

        // 设置显示模式
        self.pdfView.autoScales = YES;
        self.pdfView.displayMode = kPDFDisplaySinglePageContinuous;
        self.pdfView.displayDirection = kPDFDisplayDirectionVertical;

        // 确保第一页显示在顶部
        [self.pdfView goToPage:[self.pdfView.document pageAtIndex:0]];
    }
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.tableView.hidden = NO;
        self.tableView.top = CGRectGetMaxY(self.pdfView.frame);
        self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ self.webView.height+self.tableView.height+self.pdfView.height);
        // 隐藏 loading 指示器
        if(self.hub){
            [self.hub removeFromSuperview];
        }
        self.pdfView.hidden = NO;
        self.lineView.hidden = NO;
        self.lineView.top =  CGRectGetMaxY(self.pdfView.frame)-6;
//    });
    
}


#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DiscoverEexploreDetialListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DiscoverEexploreDetialListCell"];
    if(indexPath.row < self.dataArr.count){
        DiscoverExploreListModel *model = self.dataArr[indexPath.row];
        cell.model = model;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.dataArr.count){
        DiscoverExploreListModel *model = self.dataArr[indexPath.row];
        DiscoverExploreDetialViewController *vc = [[DiscoverExploreDetialViewController alloc]init];
        vc.exploreListModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.recommendManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [DiscoverExploreListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        self.tableView.height = 44+self.dataArr.count*90;
        if(self.exploreListModel.filePath && ![self.exploreListModel.filePath isEqualToString:@""]) {
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ self.webView.height+self.tableView.height+self.pdfView.height);
        }else{
            self.scrollView.contentSize = CGSizeMake(self.currentAvailableWidth,26+self.titleLabel.height+ self.webView.height+self.tableView.height);
        }
        [self.tableView reloadData];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"scrollView.contentSize" context:@"JPWebKitContext"];
}


@end
